<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAridPYBgISD0wFaGZWKqecTCyB0gU737HHin/8ix+HDaErTHt08tXNKRF5aPaZkj/8gJDOU2WgU0iUt7D4fUU3qR5yPqRppE7m08wQvN4bk0LpNotYKCN4Gmd5FtJUkwYw/IwhZ5dhMxSr8OP9ciGkIOvsMn1jdDSSkI2iNAzn7nRBq9lnOPiJ3+x0KcEpM87CYbR26zuRueqc1mJ/UnzcgVrqMy4PDsCWOynC39deZtaQFtvv0EGvhg3aIgQaeOFybx52J/flSu0+7XQpTlzaivuSjv5JZzHHgeetGXXsQM+7UXbQZ4B0/E37tv/i/b3Gzg4YnDEwvNsNqdYAemABQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqU+7LibJfa6+0sR/XZZjOw0VwwJxngHpG4t7lnYyo00p5tlz4R4PaasyUm1OfoNYzVJJjorRcipTobmmqk1KFzyTZdRlLFC+PItq2Mw+oXxYkrqUi0r21zncXo0yiv1bGrTdqAxMgZOWHzWSPZhLpz7VPQck4EVqHesSb9GGGalHO+rrtQC9/aJfeIzGb+MCwgdNdfzycOh25cPeDGfDe2pXnkCmFw+UCGpz+bqGnrMKdvv/Vay8Nvy0CdJTYYzjH7srowRrbJ82uW75qUggiH993RsEhXnK/FAbC0wXwjormlrCQf3gyMSLO35+1BPw0SH7LNIza95DjOj+F9VUbwIDAQAB",
        'private_key' => 'MIIEogIBAAKCAQEAqU+7LibJfa6+0sR/XZZjOw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CiXFKtXH8iqKbyTiBlfQB7u/1YRhNwu2q20Ux4laecuRgI8aXuWu10OKICMgOpoku3xd3K6BhfLd/ug6LTIwDkehlv1RoNDcSb43my9K4eEQKBgFyYGDgj8gInsycka+AK87rcgEI2VYpU7ZsgJYaSkCVtom/ITgecXmJHudQ1seSj3/brvcB8r4hDfR68IuKLMm7Ye+ko3QkMDguWgaBeYkYuP37w0dIqzFkQ7fiQL3YvFAw7sIvv5hwq7dQsMQIVZN+tvPwa03NZEgewBElsXT8PAoGAFPDwhZJCs841y5RIgQv7zgyFNOFLG62RrtuyPQtwSmXn63qJ5s+nC/q0CSnf6Aa+S+btKXk4scjBD5jH6x+EVcPBW43Re23VXRkFIX/+cFHnFoIKXBAAeUm2cuIM1GUspJ3Qi3uYAOzKduk0aAyXQbYskgjaoQNCjEQxhTM+NOE='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $useridddd = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($useridddd,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2019092467788171";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://year.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return
     * order_price_pingtai   充值的平台币数量
     * order_price           订单金额
     */
    public function alipay()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);//订单编号
        
        // 充值记录表
        $recharge_insert = [
            'recharge_user_id' => $params['user_id'],
            'recharge_money' => $params['order_price'], // 充值金额
            'recharge_type' => 2,
            'recharge_status' => 1,
            'recharge_time' => date('Y-m-d H:i:s'),
            'recharge_num' => $order_number,
            'recharge_money_pingtai' => $params['order_price_pingtai'] // 充值平台币数量
        ];
        $result = Db::table('up_recharge')->insert($recharge_insert);
        
        // 插入数据库成功，调起支付，否则返回错误
        if($result){
            $this->body = '十二年教育';
            $this->subject = '十二年教育';
//            $this->total_amount =$params['order_price'];
            $this->total_amount =0.01;
            $this->out_trade_no = $order_number;
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try{
                    $num = $getInfo['out_trade_no'];//订单号
                    // 修改订单状态
                    Db::table('up_recharge')->where('recharge_num', $num)->setField('recharge_status', 2);
    
                    // 跟新用户平台币
                    $order_info = Db::table('up_recharge')
                        ->where('recharge_num', $num)
                        ->field('recharge_money_pingtai, recharge_user_id')
                        ->find();
                    Db::table('up_u_user')->where('user_id', $order_info['recharge_user_id'])->setInc('user_balance', $order_info['recharge_money_pingtai']);
    
                    // order表
                    $order_insert = [
                        'order_type' => 1,
                        'order_price' => $order_info['recharge_money_pingtai'],
                        'order_time' => date('Y-m-d H:i:s'),
                        'order_user_id' => $order_info['recharge_user_id']
                    ];
                    Db::table('up_order')->insert($order_insert);
                    
                    Db::commit();
                    return 'success';
                }catch(\Exception $e){
                    Db::rollback();//回滚
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}